package cn.virens.common.spring.retry.annotations.expression;

import cn.virens.common.util.core.Assert;
import cn.virens.common.util.exception.APIException;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

public class VirRetryEvaluationContext extends StandardEvaluationContext {
    private static final String ATTR_VALUE = "value";

    private final AnnotationAttributes attributes;

    private Method method;
    private Class<?> clazz;

    private Object result;
    private Object[] arguments;

    public VirRetryEvaluationContext(AnnotationAttributes attributes) {
        this.attributes = Assert.isNull(attributes);
    }

    public Integer attrValue() throws APIException {
        return attributes.getNumber(ATTR_VALUE);
    }

    public Class<?> getClazz() throws APIException {
        return clazz;
    }

    public Class<?> setClass(Class<?> clazz) throws APIException {
        this.setVariable("class", clazz.getSimpleName());

        return this.clazz = clazz;
    }

    public Method getMethod() throws APIException {
        return method;
    }

    public Method setMethod(Method method) throws APIException {
        this.setVariable("method", method.getName());

        return this.method = method;
    }

    public Object getResult() throws APIException {
        return result;
    }

    public Object setResult(Object result) throws APIException {
        this.setVariable("result", result);

        return this.result = result;
    }

    public Object[] getArguments() throws APIException {
        return arguments;
    }

    public Object[] setArguments(Object[] arguments) throws APIException {
        for (int i = 0; i < arguments.length; i++) {
            this.setVariable("p" + i, arguments[i]);
            this.setVariable("a" + i, arguments[i]);
        }

        return this.arguments = arguments;
    }

}
